import { ref } from "vue";
import { defineStore } from 'pinia';
import { loginApi, userInfoApi } from "@/api/user";

export const userStore = defineStore(
  "user",
  () => {
    const user = ref(null);
    const token = ref(null);
    const isAuthenticated = ref(false);
    const login = async (credentials) => {
      try {
        // 实际项目中应该替换为真实的API调用
        const res = await loginApi(credentials);
        token.value = res.access_token;
        isAuthenticated.value = true;
      } catch (error) {
        throw error;
      }
    };
    const logout = () => {
      user.value = null;
      token.value = null;
      isAuthenticated.value = false;
    };
    const fetchUser = async () => {
      if (isAuthenticated.value) {
        try {
          const res = await userInfoApi();
          user.value = res.user;
        } catch (error) {
          logout();
        }
      }
    };
    return {
      user,
      token,
      isAuthenticated,
      login,
      logout,
      fetchUser,
    };
  },
  {
    persist: true, //持久化
  }
);
